package com.xdfsoft.homeserve.controller;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.cc.alltype.ResponseResult;
import com.jcraft.jsch.*;
import com.xdfsoft.homeserve.utils.CmdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.Map;

/**
 * @author chanchaw
 * @create 2025-05-14 8:04
 */
@CrossOrigin
@RestController
@RequestMapping("/dev")
public class DevController {
    private static final Logger logger = LoggerFactory.getLogger("cmd");
    @PostMapping("/now")
    public ResponseResult getNow(){
        return ResponseResult.ok(LocalDate.now());
    }
    @PostMapping("/execWin")
    public ResponseResult execWin(@RequestBody String cmdString) throws IOException, InterruptedException {
        CmdUtils.execWin(cmdString);
        return ResponseResult.ok("成功");
    }
    @PostMapping("/execLinux")
    public ResponseResult execLinux(@RequestBody String cmdString) throws IOException, InterruptedException {
        CmdUtils.execLinux(cmdString);
        return ResponseResult.ok("成功");
    }
    @PostMapping("/test")
    public ResponseResult test() throws JSchException {
        String HOST = "192.168.66.1";
        int PORT = 19834;
        final String USERNAME = "root";
        final String PASSWORD = "!7758ChanChaw@";

        JSch jsch = new JSch();
        Session session = null;

        try {
            // 创建SSH会话
            session = jsch.getSession(USERNAME, HOST, PORT);
            session.setPassword(PASSWORD);

            // 设置不检查主机密钥(仅用于测试环境，生产环境应配置正确的密钥)
            session.setConfig("StrictHostKeyChecking", "no");

            // 连接会话
            session.connect();
//            System.out.println("成功连接到OpenWrt设备");
            logger.info("成功连接到OpenWrt设备");

            // 打开通道并执行命令
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand("ls /home");

            // 获取命令输出
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();
            channel.connect();

            // 读取命令输出
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
//                    System.out.print(new String(tmp, 0, i));
                    logger.info(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    if (in.available() > 0) continue;
                    //System.out.println("退出状态: " + channel.getExitStatus());
                    logger.info("退出状态: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                    ee.printStackTrace();
                }
            }

            // 断开连接
            channel.disconnect();
            session.disconnect();
        } catch (JSchException e) {
//            System.err.println("SSH连接错误: " + e.getMessage());
            logger.info("SSH连接错误: " + e.getMessage());
        } catch (IOException e) {
//            System.err.println("IO错误: " + e.getMessage());
            logger.info("IO错误: " + e.getMessage());
        } finally {
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
        return ResponseResult.ok("执行完毕，请查看日志！");
    }
    @PostMapping("/getTasData")
    public ResponseResult getTasData(@RequestBody Map<String,Object> params){
        System.out.println(params);
        return ResponseResult.ok("获取TAS数据完成");
    }
}
